//
//  UIColor+Extension.m
//  Extision
//
//  Created by 岳道峰 on 2017/4/18.
//  Copyright © 2017年 hao. All rights reserved.
//

#import "UIColor+Extension.h"

static const CGFloat kFBRGBMax = 255.0f;
static const uint32_t kColorMaskRed     = 0xFF000000;
static const uint32_t kColorMaskGreen   = 0xFF0000;
static const uint32_t kColorMaskBlue    = 0xFF00;
static const uint32_t kColorMaskAlpha   = 0xFF;

UIColor *UIColorWithHexRGB(uint32_t rgbValue)
{
    uint32_t newValue = (rgbValue << 8) | kColorMaskAlpha;
    return UIColorWithHexRGBA(newValue);
}

UIColor *UIColorWithHexRGBA(uint32_t rgbaValue)
{
    //  R   G  B  A
    //0xFF FF FF FF
    uint8_t r = (rgbaValue & kColorMaskRed) >> 24;
    uint8_t g = (rgbaValue & kColorMaskGreen) >> 16;
    uint8_t b = (rgbaValue & kColorMaskBlue) >> 8;
    uint8_t a = (rgbaValue & kColorMaskAlpha) / kFBRGBMax;
    return UIColorWithRGBA(r,g,b,a);
}

UIColor *UIColorWithRGBA(uint8_t r, uint8_t g, uint8_t b, CGFloat a)
{
    return [UIColor colorWithRed:(r / kFBRGBMax)
                           green:(g / kFBRGBMax)
                            blue:(b / kFBRGBMax)
                           alpha:a];
}

UIColor *UIColorWithRGB(uint8_t r, uint8_t g, uint8_t b)
{
    return UIColorWithRGBA(r, g, b, 1.0f);
}

@implementation UIColor (Extension)

+ (UIColor *)colorWithRGB:(uint32_t)rgbValue {
    return ColorRGB(((rgbValue & 0xFF0000) >> 16),
                      ((rgbValue & 0xFF00) >> 8),
                      (rgbValue & 0xFF));
}

+ (UIColor *)colorWithRGBA:(uint32_t)rgbaValue {
    return ColorRGBA(((rgbaValue & 0xFF000000) >> 24),
                       ((rgbaValue & 0xFF0000) >> 16),
                       ((rgbaValue & 0xFF00) >> 8),
                       (rgbaValue & 0xFF));
}

+ (UIColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha {
    return ColorRGBA(((rgbValue & 0xFF0000) >> 16),
                       ((rgbValue & 0xFF00) >> 8),
                       (rgbValue & 0xFF),
                       alpha);
}

- (uint32_t)rgbValue {
    CGFloat r = 0, g = 0, b = 0, a = 0;
    [self getRed:&r green:&g blue:&b alpha:&a];
    int8_t red = r * 255;
    uint8_t green = g * 255;
    uint8_t blue = b * 255;
    return (red << 16) + (green << 8) + blue;
}

- (uint32_t)rgbaValue {
    CGFloat r = 0, g = 0, b = 0, a = 0;
    [self getRed:&r green:&g blue:&b alpha:&a];
    int8_t red = r * 255;
    uint8_t green = g * 255;
    uint8_t blue = b * 255;
    uint8_t alpha = a * 255;
    return (red << 24) + (green << 16) + (blue << 8) + alpha;
}

@end

